<template>
  <div class="org-management">
    <div class="page-header">
      <h2>{{ $t('common.orgManagement') }}</h2>
      <p>{{ $t('common.orgManagementDescription') }}</p>
    </div>
    
    <div class="search-container">
      <div class="search-item">
        <label>{{ $t('org.orgName') }}:</label>
        <InputText v-model="searchParams.orgName" placeholder="{{ $t('common.pleaseInput') }}" />
      </div>
      <div class="search-item">
        <label>{{ $t('org.status') }}:</label>
        <Dropdown
          v-model="searchParams.status"
          :options="statusOptions"
          placeholder="{{ $t('common.pleaseSelect') }}"
          optionValue="value"
          optionLabel="label"
        />
      </div>
      <div class="search-actions">
        <Button @click="search" icon="pi pi-search">{{ $t('common.search') }}</Button>
        <Button @click="reset" icon="pi pi-refresh">{{ $t('common.reset') }}</Button>
        <Button @click="handleAdd" icon="pi pi-plus" severity="success">{{ $t('common.add') }}</Button>
        <Button @click="refreshOrgTree" icon="pi pi-sync">{{ $t('common.refresh') }}</Button>
      </div>
    </div>
    
    <div class="org-container">
      <div class="org-tree">
        <h3>{{ $t('org.orgStructure') }}</h3>
        <div class="tree-content">
          <Tree
            v-if="orgTree.length > 0"
            :value="orgTree"
            :expandedKeys="expandedKeys"
            selectionMode="single"
            @nodeSelect="onNodeSelect"
          >
            <template #default="slotProps">
              <div class="tree-node-content">
                <i :class="`pi ${slotProps.node.icon}`" v-if="slotProps.node.icon"></i>
                <span>{{ slotProps.node.deptName }}</span>
                <div class="node-actions">
                  <Button @click.stop="handleAdd(slotProps.node)" icon="pi pi-plus" size="small" severity="success"></Button>
                  <Button @click.stop="handleEdit(slotProps.node)" icon="pi pi-pencil" size="small"></Button>
                  <Button @click.stop="handleDelete(slotProps.node.id)" icon="pi pi-trash" size="small" severity="danger"></Button>
                </div>
              </div>
            </template>
          </Tree>
          <div v-else class="empty-tree">
            {{ $t('org.emptyOrgTree') }}
          </div>
        </div>
      </div>
      
      <div class="org-details">
        <h3>{{ $t('org.orgDetails') }}</h3>
        <div class="details-content" v-if="selectedOrg">
          <div class="detail-item">
            <label>{{ $t('org.orgId') }}:</label>
            <span>{{ selectedOrg.id }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.orgName') }}:</label>
            <span>{{ selectedOrg.orgName }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.parentOrg') }}:</label>
            <span>{{ selectedOrg.parentOrgName || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.orgType') }}:</label>
            <span>{{ getOrgType(selectedOrg.orgType) }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.orderNum') }}:</label>
            <span>{{ selectedOrg.orderNum }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.status') }}:</label>
            <Badge :severity="selectedOrg.status === 1 ? 'success' : 'danger'">
              {{ selectedOrg.status === 1 ? $t('common.active') : $t('common.inactive') }}
            </Badge>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.leader') }}:</label>
            <span>{{ selectedOrg.leader || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.phone') }}:</label>
            <span>{{ selectedOrg.phone || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('org.email') }}:</label>
            <span>{{ selectedOrg.email || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>{{ $t('common.createTime') }}:</label>
            <span>{{ selectedOrg.createTime }}</span>
          </div>
          <div class="detail-item detail-textarea">
            <label>{{ $t('org.remark') }}:</label>
            <p>{{ selectedOrg.remark || '-' }}</p>
          </div>
        </div>
        <div v-else class="empty-details">
          {{ $t('org.selectOrgToView') }}
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <Dialog v-model:visible="dialogVisible" :header="dialogTitle" :modal="true" :style="{ width: '500px' }">
      <div class="form-container">
        <div class="form-item">
          <label>{{ $t('org.parentOrg') }}:</label>
          <Dropdown
            v-model="formData.parentId"
            :options="flattenedOrgTree"
            placeholder="{{ $t('common.pleaseSelect') }}"
            optionValue="id"
            optionLabel="deptName"
            :filter="true"
            :disabled="formData.parentId === '0' || (selectedOrg && formData.id === selectedOrg.id && !isEdit)"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('org.orgName') }} *:</label>
          <InputText v-model="formData.orgName" />
        </div>
        <div class="form-item">
          <label>{{ $t('org.orgType') }} *:</label>
          <Dropdown
            v-model="formData.orgType"
            :options="orgTypeOptions"
            optionValue="value"
            optionLabel="label"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('org.orderNum') }} *:</label>
          <InputNumber v-model="formData.orderNum" min="1" :max="999" />
        </div>
        <div class="form-item">
          <label>{{ $t('org.status') }} *:</label>
          <Dropdown
            v-model="formData.status"
            :options="statusOptions"
            optionValue="value"
            optionLabel="label"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('org.leader') }}:</label>
          <InputText v-model="formData.leader" />
        </div>
        <div class="form-item">
          <label>{{ $t('org.phone') }}:</label>
          <InputText v-model="formData.phone" />
        </div>
        <div class="form-item">
          <label>{{ $t('org.email') }}:</label>
          <InputText v-model="formData.email" />
        </div>
        <div class="form-item">
          <label>{{ $t('org.remark') }}:</label>
          <Textarea v-model="formData.remark" rows="3" />
        </div>
      </div>
      <template #footer>
        <Button @click="dialogVisible = false">{{ $t('common.cancel') }}</Button>
        <Button @click="handleSave" severity="primary">{{ $t('common.submit') }}</Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDeptStore } from '../../../store/modules/system/dept'
import type { Department } from '../../../types/app.d'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import InputNumber from 'primevue/inputnumber'
import Textarea from 'primevue/textarea'
import Dropdown from 'primevue/dropdown'
import Badge from 'primevue/badge'
import Dialog from 'primevue/dialog'
import Tree from 'primevue/tree'

const { t } = useI18n()
const deptStore = useDeptStore()

// 搜索参数
const searchParams = reactive({
  page: 1,
  pageSize: 10,
  orgName: '',
  status: null as number | null
})

// 状态选项
const statusOptions = [
  { label: t('common.active'), value: 1 },
  { label: t('common.inactive'), value: 0 }
]

// 组织类型选项
const orgTypeOptions = [
  { label: t('org.orgTypeCompany'), value: 'company' },
  { label: t('org.orgTypeDept'), value: 'dept' },
  { label: t('org.orgTypeTeam'), value: 'team' }
]

// 组织树数据
const orgTree = ref<Department[]>([])
const flattenedOrgTree = ref<Department[]>([])
const expandedKeys = ref<Record<string, boolean>>({})

// 选中的组织
const selectedOrg = ref<Department | null>(null)

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')

// 表单数据
const formData = reactive<Partial<Department>>({
  orgName: '',
  parentId: '0',
  orgType: 'dept',
  orderNum: 0,
  status: 1,
  leader: '',
  phone: '',
  email: '',
  remark: ''
})

// 初始化
const init = () => {
  loadOrgTree()
}

// 加载组织树
const loadOrgTree = async () => {
  const treeData = await deptStore.getDeptTreeAction()
  if (treeData) {
    // 由于部门数据模型和组织模型相似，这里直接使用部门数据作为组织数据
    // 在实际项目中，可能需要专门的组织API
    orgTree.value = treeData
    flattenedOrgTree.value = flattenTree(treeData)
    
    // 初始化展开状态 - 展开所有节点
    const initExpandedKeys = (nodes: Department[]) => {
      nodes.forEach(node => {
        expandedKeys.value[node.id] = true
        if (node.children && node.children.length > 0) {
          initExpandedKeys(node.children)
        }
      })
    }
    initExpandedKeys(treeData)
    
    // 默认选中根节点
    if (treeData.length > 0) {
      await deptStore.getDeptInfoAction(treeData[0].id)
      selectedOrg.value = deptStore.getCurrentDept || null
    }
  }
}

// 扁平化树结构用于下拉选择
const flattenTree = (tree: Department[]): Department[] => {
  let result: Department[] = []
  
  const flatten = (nodes: Department[], prefix = '') => {
    nodes.forEach(node => {
      const clonedNode = { ...node }
      clonedNode.deptName = prefix + clonedNode.deptName // 添加前缀显示层级
      result.push(clonedNode)
      if (node.children && node.children.length > 0) {
        flatten(node.children, prefix + '  ├─ ')
      }
    })
  }
  
  flatten(tree)
  return result
}

// 获取组织类型文本
const getOrgType = (orgType: string) => {
  const type = orgTypeOptions.find(option => option.value === orgType)
  return type ? type.label : orgType
}

// 搜索
const search = () => {
  searchParams.page = 1
  // 在实际项目中，这里应该调用专门的组织搜索API
  deptStore.getDeptListAction(searchParams)
}

// 重置
const reset = () => {
  Object.assign(searchParams, {
    page: 1,
    pageSize: 10,
    orgName: '',
    status: null
  })
  // 在实际项目中，这里应该调用专门的组织搜索API
  deptStore.getDeptListAction(searchParams)
}

// 刷新组织树
const refreshOrgTree = () => {
  loadOrgTree()
}

// 节点选择
const onNodeSelect = async (event: any) => {
  const selectedNode = event.node
  if (selectedNode && selectedNode.id) {
    await deptStore.getDeptInfoAction(selectedNode.id)
    selectedOrg.value = deptStore.getCurrentDept || null
  }
}

// 添加组织
const handleAdd = (parent?: Department) => {
  isEdit.value = false
  dialogTitle.value = t('common.add') + t('common.org')
  Object.assign(formData, {
    orgName: '',
    parentId: parent?.id || '0',
    orgType: 'dept',
    orderNum: 0,
    status: 1,
    leader: '',
    phone: '',
    email: '',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑组织
const handleEdit = async (org: Department) => {
  isEdit.value = true
  dialogTitle.value = t('common.edit') + t('common.org')
  await deptStore.getDeptInfoAction(org.id)
  if (deptStore.getCurrentDept) {
    // 由于部门数据模型和组织模型相似，这里进行字段映射
    Object.assign(formData, {
      id: deptStore.getCurrentDept.id,
      orgName: deptStore.getCurrentDept.deptName,
      parentId: deptStore.getCurrentDept.parentId,
      orgType: 'dept', // 默认为部门类型
      orderNum: deptStore.getCurrentDept.orderNum,
      status: deptStore.getCurrentDept.status,
      leader: deptStore.getCurrentDept.leader,
      phone: deptStore.getCurrentDept.phone,
      email: deptStore.getCurrentDept.email,
      remark: deptStore.getCurrentDept.remark
    })
  }
  dialogVisible.value = true
}

// 保存组织
const handleSave = async () => {
  // 由于部门数据模型和组织模型相似，这里进行字段映射
  const deptData = {
    deptName: formData.orgName,
    parentId: formData.parentId,
    orderNum: formData.orderNum,
    status: formData.status,
    leader: formData.leader,
    phone: formData.phone,
    email: formData.email,
    remark: formData.remark
  }
  
  if (isEdit.value && formData.id) {
    const success = await deptStore.updateDeptAction(formData.id, deptData)
    if (success) {
      dialogVisible.value = false
      loadOrgTree()
      deptStore.clearCurrentDept()
    }
  } else {
    const success = await deptStore.createDeptAction(deptData as Omit<Department, 'id' | 'createTime' | 'updateTime'>)
    if (success) {
      dialogVisible.value = false
      loadOrgTree()
    }
  }
}

// 删除组织
const handleDelete = async (id: string) => {
  // 检查是否有子组织
  const hasChildren = checkHasChildren(id, orgTree.value)
  if (hasChildren) {
    alert(t('org.hasChildrenCannotDelete'))
    return
  }
  
  if (confirm(t('common.confirmDelete'))) {
    const success = await deptStore.deleteDeptAction(id)
    if (success) {
      loadOrgTree()
      selectedOrg.value = null
    }
  }
}

// 检查是否有子组织
const checkHasChildren = (id: string, nodes: Department[]): boolean => {
  for (const node of nodes) {
    if (node.parentId === id) {
      return true
    }
    if (node.children && node.children.length > 0) {
      if (checkHasChildren(id, node.children)) {
        return true
      }
    }
  }
  return false
}

// 初始化加载数据
init()
</script>

<style scoped>
.org-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.search-item label {
  font-weight: 500;
  color: #333;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.org-container {
  display: flex;
  gap: 20px;
  height: calc(100vh - 300px);
}

.org-tree {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.org-details {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.org-tree h3,
.org-details h3 {
  margin: 0;
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  color: #333;
  font-size: 16px;
}

.tree-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.details-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tree-node-content {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
}

.tree-node-content:hover {
  background-color: #f3f4f6;
}

.node-actions {
  margin-left: auto;
  opacity: 0;
  transition: opacity 0.2s;
}

.tree-node-content:hover .node-actions {
  opacity: 1;
}

.node-actions .p-button {
  margin: 0 2px;
}

.empty-tree,
.empty-details {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #9ca3af;
  font-size: 14px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 4px 0;
}

.detail-item label {
  width: 100px;
  font-weight: 500;
  color: #333;
  flex-shrink: 0;
}

.detail-item span {
  flex: 1;
  word-break: break-all;
}

.detail-textarea {
  align-items: flex-start;
}

.detail-textarea p {
  flex: 1;
  margin: 0;
  word-break: break-all;
  white-space: pre-wrap;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-item label {
  font-weight: 500;
  color: #333;
}

.form-item input,
.form-item select,
.form-item .p-inputnumber,
.form-item .p-inputtextarea {
  width: 100%;
}
</style>